package com.wft.design.common.security.handler;

import com.wft.design.common.security.annotation.PreAuthorize;
import com.wft.design.common.security.bean.Authentication;
import com.wft.design.common.security.exception.AccessDeniedException;
import com.wft.design.common.security.service.AuthenticationManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

/**
 * @author WFT
 * @date 2019/12/18
 * description: 预授权程序处理器
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class PreAuthorizeAspectHandler {

    private final AuthenticationManager authenticationManager;

    @Before(value = "@annotation(preAuthorize)")
    public void before(PreAuthorize preAuthorize){
        //  认证校验
        Authentication authentication = this.authenticationManager.getAuthentication();
        if (preAuthorize.value().length > 0) {
            //  权限校验
            boolean result = authentication.getAuthorities().stream()
                    .filter(StringUtils::hasText)
                    .anyMatch(x -> PatternMatchUtils.simpleMatch(preAuthorize.value(), x));
            if (!result) {
                throw AccessDeniedException.build();
            }
        }
    }

}
